package com.wxp.demo06.storage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.wxp.demo06.R;
import com.wxp.demo06.util.FileUtil;
import com.wxp.demo06.util.LogUtils;
import com.wxp.demo06.util.ToastUtil;

import java.io.File;

/**
 * 3.2 图片写入操作
 */
public class ImageWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_content;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_image_write);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        this.setTitle("3.2 图片写入操作");

        iv_content = findViewById(R.id.iv_content);

        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_save) {
            String fileName = System.currentTimeMillis() + ".jpeg";
            // 获取当前App的私有下载目录
            File filesDir = this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            if (filesDir == null) {
                return;
            }
            path = filesDir.toString() + File.separatorChar + fileName;
            LogUtils.debug("文件地址：", path);
            // 从指定的资源文件中获取位图对象
            Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.vivo);
            // 把位图对象保存为图片文件
            FileUtil.saveImage(path, b1);
            ToastUtil.show(this, "保存成功");
            return;
        }

        if (v.getId() == R.id.btn_read) {
            //方式1：
            //Bitmap b2 = FileUtil.openImage(path);
            //iv_content.setImageBitmap(b2);

            //方式2：
            //Bitmap b2 = BitmapFactory.decodeFile(path);
            //iv_content.setImageBitmap(b2);

            //方式3：
            // 直接调用setImageURI方法，设置图像视图的路径对象
            iv_content.setImageURI(Uri.parse(path));
            return;
        }
    }
}